package com.peiqi.aiproject.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.peiqi.aiproject.dao.PlanMapper;
import com.peiqi.aiproject.dao.RegisterMapper;
import com.peiqi.aiproject.dao.SaveDataMapper;
import com.peiqi.aiproject.dao.UserMapper;
import com.peiqi.aiproject.domain.*;
import com.peiqi.aiproject.domain.dto.ValidSmsDTO;
import com.peiqi.aiproject.exception.BusinessException;
import com.peiqi.aiproject.utils.PwdUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;

/**
 * 用户业务类
 *
 * @author yulian
 */
@Slf4j
@Service
public class UserService extends ServiceImpl<PlanMapper, Plan> {
    @Resource
    UserMapper userMapper;
    @Resource
    PlanMapper planMapper;
    @Resource
    SaveDataMapper saveDataMapper;
    @Resource
    SmsService smsService;

    @Resource
    SaveDataService saveDataService;
    @Resource
    RegisterMapper registerMapper;
    @Resource
    RegisterService registerService;
    public String register(Register registerDTO) {
        //加密
        //Spring密码加密类(永远不要想着对密码进行解密)
        String encryptPassword = DigestUtils.md5DigestAsHex(("宇怜1314" + registerDTO.getUserPassword()).getBytes());
        //向数据库插入数据
        Register register = new Register();
        register.setUserAccount(registerDTO.getUserAccount());
        register.setUserPassword(encryptPassword);
        register.setInvCode(registerDTO.getInvCode());
        register.setUserData(registerDTO.getUserData());
        //使用save方法将对象保存到数据库中
        boolean saveResult = registerService.save(register);
        //如果保存失败(id未获取，即是null的话就退出)
        //索引1
        if (!saveResult) {
            return null;
        }
        return register.getUserAccount();
    }


    public User getUsers() {
        User user = (User) StpUtil.getTokenSession().get("user");
        return user;
    }

    public String saveUser(ValidSmsDTO validSmsDTO) {
        String phoneNumber = validSmsDTO.getPhoneNumber();
        User user = getUser(phoneNumber);
        if (user != null) {
            throw new BusinessException("手机号已经被注册");
        }
        if (smsService.validSms(validSmsDTO)) {
            userMapper.insert(User.builder().phoneNumber(phoneNumber).build());
            return login(LoginDTO.builder()
                    .phoneNumber(phoneNumber)
                    .code(validSmsDTO.getCode())
                    .build());
        } else {
            throw new BusinessException("验证码失效");
        }
    }

    private User getUser(String phoneNumber) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, phoneNumber));
        return user;
    }

    //添加计划
    public String plan(Plan plan) {
        Plan plan2 = new Plan();
        plan2.setPlanTitle(plan.getPlanTitle());
        plan2.setPlanText(plan.getPlanText());
        boolean saveResult = this.save(plan2);
        //如果保存失败(id未获取，即是null的话就退出)
        //索引1
        if (!saveResult) {
            return null;
        }

        return plan2.getPlanTitle();
    }

    public String login(LoginDTO loginDTO) {
        //查询我们手机号是不是存在
        User user = getUser(loginDTO.getPhoneNumber());
        if (user == null) {
            throw new BusinessException("手机号不存在");
        } else {
            //校验密码
            if (StrUtil.isNotBlank(loginDTO.getPassWord())) {
                if (!checkUserPwd(user.getPassWord(), loginDTO.getPassWord())) {
                    throw new BusinessException("手机号或密码错误");
                }
            }
            if (!smsService.validSms(ValidSmsDTO.builder()
                    .code(loginDTO.getCode())
                    .phoneNumber(loginDTO.getPhoneNumber())
                    .build())) {
                throw new BusinessException("手机号或验证码错误");
            }
            StpUtil.login(user.getPhoneNumber());
            cacheUser(user);
        }
        return StpUtil.getTokenValue();
    }


    private void cacheUser(User user) {
        StpUtil.getTokenSession().set("user", user);
    }

    private boolean checkUserPwd(String oldPwd, String loginPwd) {
        if (StrUtil.isAllNotBlank(oldPwd, loginPwd)) {
            return PwdUtil.encrypt(loginPwd).equals(oldPwd);
        } else {
            return false;
        }
    }


    public List<Plan> findAll() {
        return planMapper.selectList(null);
    }
    public List<SaveData> getdata() {
        return saveDataMapper.selectList(null);
    }

    public Register logins(Register loginDTO) {
        //加密
        //Spring密码加密类(永远不要想着对密码进行解密)
        String encryptPassword = DigestUtils.md5DigestAsHex(("宇怜1314" + loginDTO.getUserPassword()).getBytes());
        //查询用户是否存在
        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        //编写查询条件：比较账号和密码
        queryWrapper.eq("user_account", loginDTO.getUserAccount());
        queryWrapper.eq("user_password", encryptPassword);
        queryWrapper.eq("inv_code",loginDTO.getInvCode());
        queryWrapper.eq("user_data", loginDTO.getUserData());
        StpUtil.login(queryWrapper);
        StpUtil.getTokenSession().set("user", queryWrapper);
        return loginDTO;
    }

    public List<Register> getLogins() {
        System.out.println(registerMapper.selectList(null));
        return registerMapper.selectList(null);
    }

    public String deletes(Register plan) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_account", plan.getUserAccount());
        map.put("user_password", plan.getUserPassword());
        map.put("user_data", plan.getUserData());
//        int result = userMapper.deleteByMap(map);
        registerMapper.deleteByMap(map);
        return "删除成功！";
    }

    public String saveData(SaveData savedata) {
        SaveData register1 = new SaveData();
        register1.setUserData(savedata.getUserData());
        register1.setReplyData(savedata.getReplyData());
        register1.setSendAt(savedata.getSendAt());
        //使用save方法将对象保存到数据库中
        boolean saveResult = saveDataService.save(register1);
        return "";
    }
}
